<template>
  <div>
    <a-modal class="edit" v-model:visible="visible" title="编辑接口" @ok="onOk" :destroyOnClose="true" :width="680">
      <a-form :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="接口名称" v-bind="validateInfos.apiName">
          <a-input v-model:value="form.state.apiName" placeholder="请输入" maxlength="20" />
        </a-form-item>
        <a-form-item label="接口编码" v-bind="validateInfos.interfaceCode">
          <a-input v-model:value="form.state.interfaceCode" placeholder="请输入" maxlength="100" />
        </a-form-item>
        <a-form-item label="所属分组" v-bind="validateInfos.groupUuid">
          <a-tree-select v-model:value="form.state.groupUuid" :tree-data="treeData" :fieldNames="{ children: 'children', label: 'name', value: 'uuid' }" allow-clear placeholder="请选择" />
        </a-form-item>
        <a-form-item label="URL" v-bind="validateInfos.path">
          <a-row :gutter="24">
            <a-col :span="5" class="pr-0">
              请求方法
              <a-select v-model:value="form.state.method" placeholder="请选择">
                <a-select-option value="POST">POST</a-select-option>
                <a-select-option value="GET">GET</a-select-option>
                <a-select-option value="PUT">PUT</a-select-option>
                <a-select-option value="DELETE">DELETE</a-select-option>
                <a-select-option value="PATCH">PATCH</a-select-option>
                <a-select-option value="HEAD">HEAD</a-select-option>
                <a-select-option value="OPTIONS">OPTIONS</a-select-option>
                <a-select-option value="CONNECT">CONNECT</a-select-option>
                <a-select-option value="TRACE">TRACE</a-select-option>
                <a-select-option value="PURGE">PURGE</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="5" class="pr-0">
              请求协议
              <a-select v-model:value="form.state.agreement" placeholder="请选择">
                <a-select-option value="HTTPS">HTTPS</a-select-option>
                <a-select-option value="HTTP">HTTP</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="6" class="pr-0">域名<a-input v-model:value="form.state.hostDomain" placeholder="请输入" /></a-col>
            <a-col :span="7" class="pr-0">路径<a-input v-model:value="form.state.path" placeholder="请输入" /></a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model:value="form.state.basicDesc" placeholder="请输入" :auto-size="{ minRows: 2, maxRows: 5 }" maxlength="200" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { Form, message } from 'ant-design-vue'
  import { computed, reactive, ref, watch } from 'vue'
  import { useRoute } from 'vue-router'

  import { requestRecursionGroupTree } from '/@/api/manage/openApiGroup'
  import { requestEditApi } from '/@/api/manage/openApiInterface'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  const route = useRoute()
  const serviceUuid = route.query.serviceUuid as string
  const props = defineProps({
    visible: { type: Boolean, default: false },
    data: { type: Object, default: () => {} },
  })
  const treeData = ref([])
  /** 递归查询分组树 */
  const recursionGroupTree = async () => {
    const { responseCode, responseData } = await requestRecursionGroupTree({ serviceUuid })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      treeData.value = responseData
    }
  }
  recursionGroupTree()
  const emits = defineEmits(['update:visible', 'success'])
  const visible = computed({
    get: () => props.visible,
    set: (val: boolean) => emits('update:visible', val),
  })

  watch(
    () => visible.value,
    (newVal, oldVal) => {
      if (newVal && !oldVal) {
        initData()
      }
    },
  )
  const initData = () => {
    // form.state = { ...props.data }
    form.state.groupUuid = props.data.groupUuid
    form.state.apiName = props.data.apiName
    form.state.interfaceCode = props.data.interfaceCode
    form.state.basicDesc = props.data.basicDesc
    form.state.path = props.data.path
    form.state.method = props.data.method
    form.state.agreement = props.data.agreement
    form.state.hostDomain = props.data.hostDomain
  }

  /** 表单配置 */
  const form = reactive({
    state: {
      groupUuid: '',
      apiName: '',
      interfaceCode: '',
      basicDesc: '',
      hostDomain: '',
      path: '',
      method: 'POST',
      agreement: 'HTTPS',
    },
    rule: {
      apiName: [{ required: true, message: '请输入接口名称' }],
      interfaceCode: [
        {
          required: true,
          pattern: /^[A-Za-z._]+$/,
          validator: async (_, val) => {
            if (!val) return Promise.reject('请输入接口编码')
            if (!_.pattern.test(val)) {
              return Promise.reject('编码必须为字母、. 或 _ ')
            }
            return Promise.resolve()
          },
        },
      ],
      groupUuid: [{ required: true, message: '请选择所属分组' }],
      path: [{ required: true, message: '请输入路径' }],
    },
    searchSuccess: false,
    onUserPhoneSearch: () => validate('userPhone'),
  })
  /** 表单hook */
  const { validate, validateInfos } = Form.useForm(form.state, form.rule)

  /**
   * 确定
   */
  const onOk = () => {
    validate()
      .then(async () => {
        const { groupUuid, apiName, interfaceCode, basicDesc, path, method, agreement, hostDomain } = form.state
        const { responseCode } = await requestEditApi({
          uuid: props.data.uuid,
          serviceUuid,
          groupUuid,
          apiName,
          interfaceCode,
          basicDesc,
          hostDomain,
          path,
          method,
          agreement,
        })
        if (responseCode === HttpCodeEnum.SUCCESS) {
          message.success('编辑成功')
          visible.value = false
          emits('success')
        }
      })
      .catch(() => {})
  }
</script>

<style lang="less" scoped>
  .edit {
    .pr-0 {
      padding-right: 0 !important;
    }
  }
</style>
